const db = require('../db')
const Setting = require('models/Setting')

const set = async (key, value) => {
  return await db('Setting').where('key', '=', key).update({
    value: value
  })
}

const get = async (key) => {
  const result = await db('Setting').where('key', '=', key).select()
  const value = result[0] ? result[0].value : ''
  return value
}

const getEditable = async () => {
  const settings = await Setting.query((qb) => {
    qb.where('editable', 1)  
  }).fetchAll()
  return settings
}

const save = async (settings) => {
  for (let i = 0; i < settings.length; i++) {
    let setting = settings[i]
    await Setting.where({
      key: setting.key
    }).save({
      value: setting.value
    }, { patch: true })
  }
}

const getMulti = async (keys) => {
  const query = db('Setting')

  for (let i = 0; i < keys.length; i++) {
    let key = keys[i]
    if (i == 0) {
      query.where('key', '=', key)
    } else {
      query.orWhere('key', '=', key)
    }
  }
  let result = await query.select()

  result = keys.map((key) => {
    return result.filter(item => item.key === key)[0]
  })
  return result
}

module.exports = {
  set,
  get,
  save,
  getEditable,
  getMulti
}